package com.sinosoft.vaccinetoai.utils.file;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * @author xiazhihao
 * @ClassName: FileUtils
 * @ClassNameExplain:
 * @Description: 文件操作工具方式
 * @date 2024/8/1 23:30
 */
public class FileUtils {

    /**
     * http导出文件方式
     * @param filePath 文件输入的本地路径
     * @param response 文件输出的httpResponse
     * @throws Exception
     */
    public static void httpExport(String filePath, HttpServletResponse response) throws Exception{
        File file = new File(filePath);

        if (!file.exists()) {
            throw new RuntimeException("File not found");
        }

        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());

        try (FileInputStream fis = new FileInputStream(file); OutputStream os = response.getOutputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.flush();
        } catch (IOException e) {
            throw new RuntimeException("IOError writing file to output stream", e);
        }
    }

    public static String getRelativeFilePath(String fileName) {
        // 使用相对路径创建文件夹和文件
        String relativePath = "./file/";
        File fileDir = new File(relativePath);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        // 返回文件的完整路径
        return new File(fileDir, fileName).getPath();
    }

    /**
     * 字符串写出为单独的文件
     * @param data
     * @param filePath
     * @throws IOException
     */
    public static void  writeDataToFile(List<String> data, String filePath) throws IOException {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            for (String line : data) {
                writer.write(line);
                writer.newLine();
            }
        }
    }

}
